package com.example.process.work;

import com.aizuda.monitor.OshiMonitor;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
public class OSHIMonitorUtil {

    @Autowired
    private OshiMonitor oshiMonitor;


    @SneakyThrows
    public void appendProcessList(Integer limitNumber, String infoType, Map<String, Object> OSHIInfoMap) {
        // 系统前 10 个进程
        List<OSProcess> processList = this.oshiMonitor.getOperatingSystem().getProcesses(
                null, OperatingSystem.ProcessSorting.CPU_DESC, limitNumber
        );
        List<Map<String, Object>> processMapList = new ArrayList<>();

        for (OSProcess process : processList) {
            Map<String, Object> processMap = new HashMap<>(5);
            processMap.put("name", process.getName());
            processMap.put("pid", process.getProcessID());
            long time=System.currentTimeMillis()-process.getStartTime();
            processMap.put("useTime", TimeChange.start(time));
            processMap.put("startTime", process.getStartTime());
            processMap.put("cpu", this.oshiMonitor.formatDouble(process.getProcessCpuLoadCumulative()));
            processMapList.add(processMap);
        }
        OSHIInfoMap.put(infoType, processMapList);
    }



    @SneakyThrows
    public void appendDataInOSHIInfoMap(String infoType, Map<String, Object> OSHIInfoMap) {

        switch (infoType) {
            // 系统前10个进程信息
            case "processList":
                this.appendProcessList(10, infoType, OSHIInfoMap);
                break;
        }

    }

    @SneakyThrows
    // get oshi info function
    public Map<String, Object> GetOSHIInfo(List<String> infoTypeList) {

        Map<String, Object> OSHIInfoMap = new HashMap<>(5);

        for (String infoType: infoTypeList) {

            this.appendDataInOSHIInfoMap(infoType, OSHIInfoMap);

        }

        return OSHIInfoMap;

    }

}
